# Create your views here.
from django.http import HttpResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from musicmanager.models import Music,Annoation,Lyric
from correcterror.models import Action,MusicError
from django.shortcuts import render_to_response,redirect
from django.template.loader import render_to_string
from django.core.files.uploadhandler import FileUploadHandler 
from django import forms

import simplejson
import datetime
import random
import os
import shutil

appprefix = "/mysite"

#only change the audio need the operation of 
#upload the right music
def index(request):
    errorlist = MusicError.objects.order_by('-date')[0:10]
    render_to_response('listen.html',{'errorlist':errorlist})

def correctname(request):
    musicid = request.GET['musicid']
    name = request.GET['name']
    musicl = Music.objects.filter(id__exact=musicid)
    if musicl.count() != 1:
        return HttpResponse("modify error")
    else:
        music = musicl[0]
        orgname = music.name
        music.name = name
        music.save()
        addAction(request.user,musicid,"change name of music"+" from "+orgname+str(musicid)+" to "+name)
        return HttpResponse("ok")

def correctsinger(request):
    musicid = request.GET['musicid']
    singer = request.GET['singer']
    musicl = Music.objects.filter(id__exact=musicid)
    if musicl.count() != 1:
        return HttpResponse("modify error")
    else:
        music = musicl[0]
        orgsinger = music.singer
        music.singer = singer
        music.save()
        addAction(request.user,musicid,"change singer of music"+str(musicid)+" from "+orgsinger+" to "+singer)
        return HttpResponse("ok")

def correctalbum(request):
    musicid = request.GET['musicid']
    album = request.GET['album']
    musicl = Music.objects.filter(id__exact=musicid)
    if musicl.count() != 1:
        return HttpResponse("modify error")
    else:
        music = musicl[0]
        orgalbum = music.album
        music.album = album
        music.save()
        addAction(request.user,musicid,"change album of music"+str(musicid)+" from "+orgalbum+" to "+album)
        return HttpResponse("ok")

def correctbasicinfo(request):
    musicid = request.GET['musicid']
    album = request.GET['album']
    name = request.GET['name']
    singer = request.GET['singer']
    musicl = Music.objects.filter(id__exact=musicid)
    if musicl.count() != 1:
        return HttpResponse("modify error")
    else:
        music = musicl[0]
        orgalbum = music.album
        orgname = music.name
        orgsinger = music.singer
        music.album = album
        music.name = name
        music.singer = singer
        music.save()
        addAction(request.user,musicid,"change album of music"+str(musicid)+" from "+orgalbum+" to "+album+" from "+orgsinger+" to "+singer+" from "+orgname+" to "+name)
        dic ={}
        dic['status'] = "ok"
        return HttpResponse(simplejson.dumps(dic))

def correctlyric(request):
    musicid = request.GET['musicid']
    modifylyric = request.GET['lyric']
    lyriclist = Lyric.objects.filter(music__id__exact=musicid)
    if lyriclist.count() != 1:
        return HttpResponse("modify error")
    else:
        lyric = lyriclist[0]
        orglyric = lyric.lyric
        lyric.lyric = modifylyric
        lyric.save()
        addAction(request.user,musicid,"change lyric of music"+str(musicid)+" from "+orglyric+" to "+modifylyric)
        dic ={}
        dic['status'] = "ok"
        return HttpResponse(simplejson.dumps(dic))


class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file  = forms.FileField()


def correctaudio(request):
    if request.method == 'POST':
        mid = request.POST['musicid']
        if mid == -1:
            #should not happen
            return redirect('/')
        #get the orgmusic
        musicl = Music.objects.filter(id__exact=mid)
        if musicl.count() != 1:
            return HttpResponse("error music index")
        else:
            music = musicl[0]
        
        #write to file
        destination = open('E:/musicdir/addmusic/'+music.name+"_"+music.singer+".mp3", 'wb+')
        for chunk in request.FILES['file1'].chunks():
            destination.write(chunk)
        destination.close()

        #move the orgmusic
        try:
            fullpath = "E:"+music.musiclink
            dirpath = fullpath[0:fullpath.rfind('/')]
            name = fullpath[fullpath.rfind('/')+1:len(fullpath)]
            if os.listdir(dirpath).count(name) != 0:
                shutil.move("E:"+music.musiclink,"E:/musicdir/deletemusic/"+music.name+"_"+music.singer+".mp3")
                #shutil.move("E:"+music.musiclink.encode("gbk"),"E:/deletemusic"+music.musiclink.encode("gbk"))
        except Exception,e:
            #todo check whether the file exist
            return HttpResponse(str(e))
        
        #change the annoation status
        music.musiclink = "/musicdir/addmusic/"+music.name+"_"+music.singer+".mp3"
        music.save()
        alist = Annoation.objects.filter(music__id__exact=mid).filter(ok__exact=True)
        for a in alist:
            a.pvalue = -1
            a.avalue = -1
            a.dvalue = -1
            a.ok = false
            a.save()
            
        addAction(request.user,mid,"change audio of music"+str(mid)+" "+music.name+"_"+music.singer)
        return redirect(appprefix)
    else:
        return redirect(appprefix)
    

"""
    #uploadfile,the orgfile should now be delete be to be modify as another name
    #how to handle file upload in the server
    #open this in a window
    musicid = request.GET['musicid']
    lyric = request.GET['lyric']

    #get part
    #return the musicinfo and the render page
    

    #post part
    addAction(request.user,musicid,"change audio of music"+str(musicid)+Music.objects.filter(id__exact=musicid)[0].name)
    return HttpResponse()
"""

def adderror(request):
    #should be an interface or just a api?
    a = 1
#user and music must exist
def addAction(user,musicid,action):
    music = Music.objects.filter(id__exact=musicid)[0]
    ac = Action()
    ac.user = user
    ac.music = music
    ac.action = action
    ac.save()

"""
show the action to this music
use template to render
"""
def showmodify(request):
    try:
        musicid = request.GET['musicid']
        alist = Action.objects.filter(music__id__exact=musicid).order_by('-date')
        if alist.count() == 0:
            dic = {}
            dic['status'] = "error"
            dic['errordesp'] = "norecord"
            return HttpResponse(simplejson.dumps(dic))
        else:
            dic = {}
            dic['status'] = "ok"
            dic['htmlcode'] = render_to_string('modifyrecord.html',{'recordlist':alist})
            return HttpResponse(simplejson.dumps(dic))
    except Exception,e:
        dic = {}
        dic['status'] = "error"
        dic['errordesp'] = str(e)
        return HttpResponse(simplejson.dumps(dic))
    
